package com.sinven.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sinven.entity.BaseMessage;
import com.sinven.pojo.Wechatsign;
import com.sinven.util.EncryptUtil;
import com.sinven.util.WechaUtil;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@Scope(value = "prototype")
@ParentPackage(value = "json-default")
public class WechatAction extends ActionSupport implements ModelDriven<Wechatsign> {
    Wechatsign wechatsign=new Wechatsign();
    private static String token = "ttttttttt";
    @Override
    public Wechatsign getModel() {
        return wechatsign;
    }

    @Action(value = "wechat",results = {@Result(type = "json")})
    public String receiveSignature() throws IOException, DocumentException {
        HttpServletRequest req=ServletActionContext.getRequest();
        HttpServletResponse resp = ServletActionContext.getResponse();
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //得到请求过来的方法判断是post还是get
        String method=req.getMethod();
        if ("GET".equalsIgnoreCase(method)){
            doGet(out);
        }else{
            System.out.println();
            doPost(req,out);

        }


        return NONE;

    }

    private void doPost(HttpServletRequest req,PrintWriter out) throws IOException, DocumentException {
        //dom4j
        Map<String,Object> map= WechaUtil.XmlToMap(req);
        if("text".equalsIgnoreCase(map.get("MsgType").toString())){
            BaseMessage message=new BaseMessage();
            message.setCreateTime(new Date().getTime());
            message.setFromUserName(map.get("ToUserName").toString());
            message.setContent(map.get("Content").toString());


            message.setMsgType(map.get("MsgType").toString());

            message.setToUserName(map.get("FromUserName").toString());

            String  s=WechaUtil.outXml(message);

            out.print(s);

        }



    }

    private void doGet(PrintWriter out) {

        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] temp = {token,wechatsign.getTimestamp(),wechatsign.getNonce()};
        Arrays.sort(temp);

        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuffer sb = new StringBuffer();
        for (String str : temp){
            sb.append(str);
        }
        System.out.println(sb.toString());

        //加密
        String sha1 = EncryptUtil.getSha1(sb.toString());

        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if(wechatsign.getSignature().equals(sha1)){
            System.out.println("校验成功");
            //4)若确认此次GET请求来自微信服务器，请原样返回echostr参数内容
            out.print(wechatsign.getEchostr());

        }else {
            out.print("非法请求");
        }
        //说明请求不是来自微信服务器

    }


}
